<!-- eslint-disable vue/no-v-html -->
<template>
  <div id="displayMessage" v-html="displayMessage" />
</template>
<script lang="ts" setup>
import { type MainItemVo, EAnswerState } from '@/api/type'
import { scroll, transformMsg } from '@/utils'
import { computed, inject, ref, watch, nextTick, onMounted } from 'vue'
import { TransitionPresets, useTransition } from '@vueuse/core'
import { onBeforeUnmount } from 'vue';

const props = withDefaults(defineProps<MainItemVo>(), {
  isLastOne: false,
  message: '1',
  plainText: '2',
  hasCursor: false,
  isMultiNode: false,
  isAnswering: false,
  id: '',
  answerId: '',
  subIndex: 0
})
const emit = defineEmits(['changePage'])
// const showIndex = ref(props.message.length ? props.message.length : 10)

const fakeMessage = ref('')
const showIndex = computed(() => {
  return fakeMessage.value.length ? fakeMessage.value.length : 10
})
const showIndexTransition = useTransition(showIndex, {
  transition: TransitionPresets.linear,
  duration: 1000,
  // 禁用动画效果，多节点的情况下，判断是不是历史记录的， isHistory
  disabled: !props.isLastOne || ((!!props.replyState || props.answerState === 5) && props.isLastOne) || (props.isMultiNode && props.isHistory)
})
const timer = ref<number | null>(null)
const updateFlowing = inject('updateFlowing', () => {}) as (answerId: string, isFlowing: boolean, subIndex: number) => void

const scrollTimeout = ref()
watch(
  () => props.message,
  (newVAl) => {
    let lastMessage = transformMsg(newVAl).replace(
      /\[\[(.*?)\]\]/g,
      `<span class="pageIndex" data-index="$1" data-chat=${props.id}></span>`
    )
    if(props.isMultiNode && props.answerState > EAnswerState.ANSWERING) {
      updateFlowing(props.answerId,false,props.subIndex)
    }
    if(props.isHistory && !props.isFlowing) {
      fakeMessage.value = lastMessage
      scrollTimeout.value = setTimeout(() => {
        toBottom?.()
      },2000)
      return
    }
    if ((props.replyState && !props.isLastOne) || (props.isLastOne && !props.isAnswering)) {
      fakeMessage.value = lastMessage
      updateFlowing(props.answerId,false,props.subIndex)
      if(props.isLastOne) {
        scrollTimeout.value = setTimeout(() => {
          toBottom?.()
        },1000)
      }
      return
    }
    if (newVAl && props.isLastOne) {
      // let count = lastMessage.length / 20
      // const result = lastMessage.match(/.{1,20}/g) || []
      // let countNum = 0
      // timer.value = setInterval(() => {
      //   updateFlowing(props.answerId,true,props.subIndex)
      //   console.warn('countNum', countNum)
      //   if (countNum > count) {
      //     fakeMessage.value = lastMessage
      //     clearInterval(Number(timer.value))
      //     updateFlowing(props.answerId,false,props.subIndex)
      //     return
      //   }
      //   fakeMessage.value += result[countNum]
      //   ++countNum
      // }, 1000)
      updateFlowing(props.answerId,true,props.subIndex)
      fakeMessage.value = lastMessage
    }
  },
  {
    immediate: true
  }
)
const displayMessage = computed(() => {
  // console.log(32132,  showIndexTransition.value)
  return  fakeMessage.value?.slice(0, showIndexTransition.value) +
      (props?.replyState
        ? ''
        : ((props?.answerState || 0) <= EAnswerState.ANSWERING && !props.isMultiNode) ||
            (props.isMultiNode && props.hasCursor)
          ? '<span class="animation-blink">|</span>'
          : '')
  
})
watch(
  displayMessage,
  () => {
    nextTick(() => {
      const fn = (e) => {
        changePageClick(
          e.target.dataset.index as unknown as number,
          e.target.dataset.chat as unknown as string,
          e
        )
      }
      document.querySelectorAll('.pageIndex').forEach((el) => {
        el.removeEventListener('click', fn)
        el.addEventListener('click', fn)
      })
     
    })
  },
  { immediate: true }
)
watch(
  () => props.message,
  (newVAl) => {
    showIndex.value = newVAl.length
  }
)

watch(showIndex, () => {
  toBottom?.()
})

const toBottom = inject(scroll, () => {
  console.log('noinject')
})
const changePageClick = (index: number, id: string,e: Event) => {
  let allDom = document.querySelectorAll('.pageIndexActive')
  allDom.forEach((el) => {
    el.classList.remove('pageIndexActive')
  })
  e.target?.classList.add('pageIndexActive')
  if (id == props.id) {
    emit('changePage', { index, id })
  }
}
onBeforeUnmount(() => {
  clearInterval(Number(timer.value))
  clearTimeout(Number(scrollTimeout.value))
})
</script>
<style lang="scss">
.pageIndex {
  cursor: pointer;
  background-image: url('@/static/image/referenceGuideIcon.png');
  border-radius: 50%;
  padding: 2px 10px;
  margin-left: 5px;
  background-size: contain;
  background-repeat: no-repeat;
}
.pageIndex:hover {
  background-image: url('@/static/image/referenceGuideIconHover.png');
}
.pageIndexActive{
  background-image: url('@/static/image/referenceGuideIconActived.png'); 
}
table{
  border: 1px solid #ddd;
    border-collapse: separate;
    border-left: 0;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    border-bottom:0 ;
}
table th, table td {
  border-left: 1px solid #ddd;
  // border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}
</style>
